var ImageFile;

function listenFileSelect() {
    // listen for file selection 
    var fileInput = document.getElementById("mypicInput"); // pointer #1 
    // When a change happens to the File Chooser Input 
    fileInput.addEventListener('change', function (e) {
        ImageFile = e.target.files[0];   //Global variable 
        var imageurl = URL.createObjectURL(ImageFile);
        console.log(imageurl);
        updateImage(imageurl);
    })
}
listenFileSelect();

function updateImage(imageurl) {
    const image = document.getElementById("mypic-goes-here"); // pointer #2 
    image.src = imageurl; // Display this image 
}



function savePost() {
    // Gather the data from the form 
    var calorieData = document.getElementById('calorieInput').value;
    var details = document.getElementById('detailsText').value;
    var image = document.getElementById('mypicInput').files[0];

    const now = new Date();
    const dformatted = now.toLocaleString('en-US', {
        weekday: 'short',  // "Monday", "Tuesday", etc. 
        year: 'numeric',  // "2021", "2022", etc. 
        month: 'short',    // "January", "February", etc. 
        day: 'numeric',   // 1, 2, 3, etc. 
        hour: 'numeric',  // 12 AM, 1 PM, etc. 
        minute: 'numeric',
        second: 'numeric'
    });

    var formData = {
        date: dformatted,       //save the date 
        calories: calorieData,  //save the calorie entered 
        details: details,
        imageName: image.name // Store image name as a reference 
    }; //js object


    addToPostHistory(formData);

}

function addToPostHistory(data) {
    console.log("addHistory");
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    if (user) {
        var users = JSON.parse(localStorage.getItem("users"));
        var email = user["email"];  //email of who is logged in 

        const person = users.find(u => u.email === email);
        if (person.history === null)      //if there are no users yet 
            person.history = [];          //initialize it to empty 

        // pushes it to the "person" object 
        person.history.push(data);

        localStorage.setItem("users", JSON.stringify(users));
        //addCountLocalStorage(data.calories); 
        updateCount(data.calories);
        alert('Data saved successfully!');

    } else {
        console.log("No one is logged in");
    }
}

function updateCount(calories){
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    var users = JSON.parse(localStorage.getItem("users"));
    var email = user["email"];  //email of who is logged in 

    const person = users.find(u => u.email === email); 
    person.count = Number(person.count) + Number(calories); 

    localStorage.setItem("users", JSON.stringify(users)); 


}





